package com.yunhe.transfer.config;

import cn.beepower.domain.bus.MqttDataBus;
import cn.beepower.domain.mqtt.client.MQTT;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;

@Configuration
public class MqttConfig {

    @Value("${mqtt.username}")
    private String username;
    @Value("${mqtt.password}")
    private String password;
    @Value("${mqtt.host}")
    private String host;

    private static final Logger logger = LoggerFactory.getLogger(MqttConfig.class);

    @Bean(name = "MqttDataBus")
    public MqttDataBus getDataBus() {
        MQTT mqtt = new MQTT();
        mqtt.setUserName(username);
        mqtt.setPassword(password);
        logger.info("MqttDataBus地址：{}", host);
        try {
            mqtt.setHost(host);
        } catch (Exception e) {
            logger.error("错误的mqtt Url", e);
        }
        mqtt.setClientId(UUID.randomUUID().toString());
        return new MqttDataBus(mqtt);
    }

    @Bean(name = "mqttClient")
    public MqttClient getMqttClient() throws Exception {
        // MemoryPersistence设置clientId的保存形式，默认为以内存保存
        logger.info("MqttClient地址：{}", host);
        MqttClient mqttClient = new MqttClient(host, UUID.randomUUID().toString(), new MemoryPersistence());
        // MQTT的连接设置
        MqttConnectOptions options = new MqttConnectOptions();
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
        options.setCleanSession(true);
        // 设置连接的用户名
        options.setUserName(username);
        // 设置连接的密码
        options.setPassword(password.toCharArray());
        // 设置超时时间 单位为秒
        options.setConnectionTimeout(10);
        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
        options.setKeepAliveInterval(20);
        // 设置自动重连
        options.setAutomaticReconnect(true);
        mqttClient.connect(options);
        return mqttClient;
    }
}
